package com.stream.cloud.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.stream.cloud.model.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yebaokang on 2017/11/3.
 */

@Service

@Slf4j
public class UserService {

    public static final String SERVICE_NAME = "cloud-simple-service";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private FeignUserService feignUserService;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    public List<UserEntity> queryAll() {

        ServiceInstance service = loadBalancerClient.choose(SERVICE_NAME);
        log.info("queryAll ->> service:{}", service);
        String url = "http://" + service.getHost() + ":" + service.getPort() + "/user";

        log.info("queryAll ->> URL:{}", url);
        log.info("queryAll ->> getUri:{}", service.getUri());

        List list = restTemplate.getForObject(url, List.class);
        log.info("queryAll ->> list:" + list);

        return list;

//        return restTemplate.getForObject(url, List.class);
    }

    @HystrixCommand(fallbackMethod = "fallbackSearchAll")
    public List<UserEntity> searchAll() {
//        List list = restTemplate.getForObject("http://" + SERVICE_NAME + "/user", List.class);
        List<UserEntity> list = feignUserService.readUserInfo();

        log.info("searchAll ->> list:" + list);

        return list;
    }

    private List<UserEntity> fallbackSearchAll() {
        log.info("HystrixCommand fallbackMethod handle!");
        List<UserEntity> users = new ArrayList<UserEntity>(1);
        UserEntity user = new UserEntity();
        user.setUserName("TestHystrixCommand");
        users.add(user);

        return users;
    }
}
